package org.gd.hellojaxb.privatzvit;

import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.XNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

/*import javax.servlet.http.HttpServletRequest;*/
import javax.xml.bind.annotation.*;
import java.util.*;

@XmlRootElement(name = "user")
@XmlAccessorType(XmlAccessType.NONE)
public class User {

    private static final Logger logger = LoggerFactory.getLogger(User.class);

    @XmlElement
    private long uid = 0;
    @XmlElement
    private String login = "";
    @XmlElement
    private int role = 0;
    @XmlElement
    private String pwd = "";
    @XmlElement
    private String name = "";
    @XmlElement
    private String fname = "";
    @XmlElement
    private String lname = "";
    /**
     * 1: разблокированый
     * -1: заблокированый
     */
    @XmlElement
    private int status = 0;
    @XmlElement
    private String need_change_pwd = "N";
    @XmlElement
    private boolean is_auth = false;
    @XmlElement
    private String email = "";
    @XmlElement
    private String edrpou = "";
    @XmlElement
    private String sesion_pwd = "";
    @XmlElement
    private String sessionKey;
    @XmlElement(name = "item")
    @XmlElementWrapper(name = "list")
    private List<Organization> listOrg = new ArrayList<Organization>() {{
        add(new Organization());
        add(new Organization());
    }};
    @XmlElement
    private ClientSetting cs;

    public User() {
    }

    public User(long uid, String name, String sessionKey, ClientSetting cs) {
        this();
        this.uid = uid;
        this.name = name;
        this.sessionKey = sessionKey;
        this.cs = cs;
    }

    public User(long uid, String name, String sessionKey, String edrpou, ClientSetting cs) {
        this(uid, name, sessionKey, cs);
        this.edrpou = edrpou;
    }

    public User(long uid, String login, int role, String pwd, String name, String fname, String lname, int status, String need_change_pwd, String email) {
        this.uid = uid;
        this.login = login;
        this.role = role;
        this.pwd = pwd;
        this.name = name;
        this.fname = fname;
        this.lname = lname;
        this.status = status;
        this.need_change_pwd = need_change_pwd;
        this.email = email;

    }

    public User(List<Hashtable> param) {
        if (!param.isEmpty()) {
            if (param.size() > 0) {
                Hashtable h = param.get(0);
                this.uid = Long.parseLong(h.get("ID").toString());
                this.login = h.get("LOGIN").toString();
                this.role = Integer.parseInt(h.get("ROLE_ID").toString());
                this.pwd = h.get("PWD").toString();
                this.name = h.get("NAME").toString();
                this.fname = h.get("FIRSTNAME").toString();
                this.lname = h.get("LASTNAME").toString();
                this.status = Integer.parseInt(h.get("USER_STATUS").toString());
                this.need_change_pwd = h.get("NEED_CHANGE_PWD").toString();
                this.email = h.get("ROUTE").toString();
            }
        }
    }

    public void auth() {
        this.is_auth = !(this.sessionKey == null || this.sessionKey.isEmpty());
    }

    public String getFio() {
        /*return this.cs == null ? this.name : this.cs.getFirmNm();*/
        return "getFio";
    }

    /**
     * @return the uid
     */
    public Long getUid() {
        return uid;
    }

    /**
     * @param uid the uid to set
     */
    public void setUid(Long uid) {
        this.uid = uid;
    }

    /**
     * @return the login
     */
    public String getLogin() {
        return login;
    }

    /**
     * @param login the login to set
     */
    public void setLogin(String login) {
        this.login = login;
    }

    /**
     * @return the role
     */
    public int getRole() {
        return role;
    }

    /**
     * @param role the role to set
     */
    public void setRole(int role) {
        this.role = role;
    }

    /**
     * @return the pwd
     */
    public String getPwd() {
        return pwd;
    }

    /**
     * @param pwd the pwd to set
     */
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the fname
     */
    public String getFname() {
        return fname;
    }

    /**
     * @param fname the fname to set
     */
    public void setFname(String fname) {
        this.fname = fname;
    }

    /**
     * @return the lname
     */
    public String getLname() {
        return lname;
    }

    /**
     * @param lname the lname to set
     */
    public void setLname(String lname) {
        this.lname = lname;
    }

    /**
     * @return the status
     */
    public int getStatus() {
        return status;
    }

    /**
     * @param status the status to set
     */
    public void setStatus(int status) {
        this.status = status;
    }

    /**
     * @return the need_change_pwd
     */
    public boolean getNeed_change_pwd() {
        return need_change_pwd.equals("Y");
    }

    /**
     * @param need_change_pwd the need_change_pwd to set
     */
    public void setNeed_change_pwd(String need_change_pwd) {
        this.need_change_pwd = need_change_pwd;
    }

    /**
     * @return the is_auth
     */
    public boolean isAuth() {
        return is_auth;
        /*return true;*/
    }

    /**
     * @param is_auth the is_auth to set
     */
    public void setIs_auth(boolean is_auth) {
        this.is_auth = is_auth;
    }

    /**
     * @return the sesion_pwd
     */
    public String getSesion_pwd() {
        return sesion_pwd;
    }

    /**
     * @param sesion_pwd the sesion_pwd to set
     */
    public void setSesion_pwd(String sesion_pwd) {
        this.sesion_pwd = sesion_pwd;
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    public String getSessionKey() {
        return sessionKey;
    }

    public void setSessionKey(String sessionKey) {
        this.sessionKey = sessionKey;
    }

    /**
     * @return the edrpou
     */
    public String getEdrpou() {
        return edrpou;
    }

    /**
     * @param edrpou the edrpou to set
     */
    public void setEdrpou(String edrpou) {
        this.edrpou = edrpou;
    }

    public ClientSetting getClientSetting() {
        return cs;
    }

    public void setClientSetting(ClientSetting cs) {
        this.cs = cs;
    }

    public List<Organization> getListOrg() {
        return listOrg;
    }

    public void setListOrg(List<Organization> listOrg) {
        this.listOrg = listOrg;
    }

    public String getListOrgXml() {
        StringBuilder sb = new StringBuilder();
        sb.append("<ORGS>");
        for (Organization org: getListOrg()) {
            sb.append(org.toXml());
        }
        sb.append("</ORGS>");
        return sb.toString();
    }

    /*public void saveClientParam(HttpServletRequest req, Document doc) throws Exception {
        Map<Integer, String> in_param = new HashMap<Integer, String>();

        Enumeration e = req.getParameterNames();
        Map map = req.getParameterMap();
        int id = 0;
        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String val = req.getParameter(key);
            if (val != null && !val.isEmpty()) {
                //DomUtils.SetNodeValue(doc, key, val);
            }
            Object obj = map.get(key + "_description");
            if (obj != null && obj instanceof String[] && ((String[]) obj).length > 0) {
                String[] vals = (String[]) obj;
                //DomUtils.SetAttrNode(doc, key, "description", vals[0]);
            }
        }

        //ClientSetting newcs = new ClientSetting(DomUtils.downloadXML(doc));

        //DB db = new DB();

        String type = req.getParameter("TYPE") == null ? "0" : req.getParameter("TYPE");
        in_param.put(1, type);
        in_param.put(2, getEdrpou());
        //in_param.put(3, newcs.toXml());

        //id = db.saveClob("sql.save.client.param", in_param);

        saveLeaders(doc, String.valueOf(id));
        //setClientSetting(newcs);
    }*/

    public void saveLeaders(Document doc, String idClient) throws Exception {
        Map<Integer, String> in_param = new HashMap<Integer, String>();
        //DB db = new DB();
        int size = 0;
        //бухгалтера
        XNumber xn = (XNumber) XPathAPI.eval(doc, "count(//*/T1RXXXXG1S)");
        size = Integer.parseInt(xn.str());
        for (int i = 1; i <= size; i++)
        {
            String NUMIDENT = XPathAPI.eval(doc, "string(//*/T1RXXXXG1S[position() = '" + i + "'])").str();
            if (!NUMIDENT.equals(""))
            {
                String FIO = XPathAPI.eval(doc, "string(//*/T1RXXXXG2S[position() = '" + i + "'])").str();
                String COD_TITLE = "1";
                String EKB_ID = "";
                try {
                    //EKB_ID = EKBConnector.getEKBUserId(NUMIDENT);
                } catch (Exception e) {
                    logger.error("[saveLeaders]: ", e);
                }

                if (!EKB_ID.isEmpty()) {
                    in_param = new HashMap<Integer, String>();
                    in_param.put(1, idClient);
                    in_param.put(2, NUMIDENT);
                    in_param.put(3, FIO);
                    in_param.put(4, "Бухгалтер");
                    in_param.put(5, COD_TITLE);
                    in_param.put(6, EKB_ID);
                    in_param.put(7, getEdrpou());

                    //db.exec("sql.save.leader.param", in_param);
                }
            }
        }
        //директора
        xn = (XNumber) XPathAPI.eval(doc, "count(//*/T2RXXXXG1S)");
        size = Integer.parseInt(xn.str());
        for (int i = 1; i <= size; i++) {
            String NUMIDENT = XPathAPI.eval(doc, "string(//*/T2RXXXXG1S[position() = '" + i + "'])").str();
            if (!NUMIDENT.isEmpty()) {
                String FIO = XPathAPI.eval(doc, "string(//*/T2RXXXXG2S[position() = '" + i + "'])").str();
                String COD_TITLE = "2";
                String EKB_ID = "";
                try {
                    //EKB_ID = EKBConnector.getEKBUserId(NUMIDENT);
                } catch (Exception e) {
                    logger.error("[saveLeaders]: ", e);
                }
                if (!EKB_ID.isEmpty()) {
                    in_param = new HashMap<Integer, String>();
                    in_param.put(1, idClient);
                    in_param.put(2, NUMIDENT);
                    in_param.put(3, FIO);
                    in_param.put(4, "Керівник");
                    in_param.put(5, COD_TITLE);
                    in_param.put(6, EKB_ID);
                    in_param.put(7, getEdrpou());

                    //db.exec("sql.save.leader.param", in_param);
                }
            }
        }
    }

    @SuppressWarnings("unused")
    public void reloadListOrganizations(){
        try{
            //ClientDao cd = new ClientDao();
            //List<Organization> organizations = cd.getOrganizationsByEkbId(Long.toString(getUid()));
            /*if(organizations == null || organizations.isEmpty()){
                this.setListOrg(new ArrayList<Organization>());
            } else {
                this.setListOrg(organizations);
            }*/
        } catch (Exception ex){
            logger.error("", ex);
            ex.printStackTrace();
        }
    }
}

